<?php
	/**
	 * @ignore 
	 */
	if( defined("apl_".__FILE__) ) return;
	define("apl_".__FILE__,"apl_".__FILE__);
	  
	require_once(APL_ROOT."/apl_constants.php");
  	/**
  	 * Helper class for image operations
  	 * 
  	 * @package apl
 	 * @subpackage helpers
  	 */
	class AplGraphicsHelper{
      
	  	public static function checkGD(){
	    	if (!extension_loaded('gd') && !extension_loaded('gd2'))
	        	return false;
	        else
	        	return true;
	    }
      	/**
      	 * Create a thumbnail of the source image
      	 *
      	 * @param String $paramSourceImage 		: Source Image
      	 * @param String $paramThumbDir 		: Path To Thumbnail
      	 * @param String $paramMaxSideLength 	: Max size of the thumbnail (width or height )
      	 * @param String $paramThumbPrefix 		: prefix for thumbnail files
      	 */
		public static function createThumb( $paramSourceImage, 
											$paramThumbDir, 
											$paramMaxSideLength, 
											$paramThumbPrefix = 'th_' 
										)
	    {
	    	if( !file_exists($paramSourceImage) )
	        	throw new Exception('File '.$paramSourceImage.' does not exists!',EX_FILE_NOT_EXISTS);
	       	
	        $imgInfo = getimagesize( $paramSourceImage );
	          
			switch( $imgInfo[2] )
			{
			    case 1: 
			        $srcImgH = imagecreatefromgif($paramSourceImage); 
			        break;
			    case 2: 
			        $srcImgH = imagecreatefromjpeg($paramSourceImage);  
			        break;
			    case 3: 
			        $srcImgH = imagecreatefrompng($paramSourceImage); 
			        break;
			    default:
			        throw new Exception('Unknown image format!',EX_UNKNOWN_IMAGE_FORMAT);
			}  
			$newWidth    = $imgInfo[0];           
			$newHeight   = $imgInfo[1];
			//Width is bigger than height
			if( $imgInfo[0] > $imgInfo[1] )
			{
				if( $imgInfo[0] > $paramMaxSideLength )
				{
			    	$newHeight = round( ( $imgInfo[1] )* ($paramMaxSideLength*100/$imgInfo[0] )/100 );          
			    	$newWidth  = $paramMaxSideLength;
				}
			}
			else
			{
				if( $imgInfo[1] > $paramMaxSideLength  )
				{              
			    	$newWidth  = round( ( $imgInfo[0] )* ($paramMaxSideLength*100/$imgInfo[1] )/100 );
			    	$newHeight = $paramMaxSideLength;
				}
			}
			
			$thumbImgH = imagecreatetruecolor( $newWidth, $newHeight );
			imagecopyresampled($thumbImgH, $srcImgH , 0, 0, 0, 0, $newWidth, $newHeight, $imgInfo[0], $imgInfo[1]);
			$thumbFile = $paramThumbDir.$paramThumbPrefix.basename($paramSourceImage);          
			                 
			switch ($imgInfo[2]) 
			{
			    case 1: 
			        imagegif( $thumbImgH , $thumbFile); 
			        break;
			    case 2: 
			        imagejpeg( $thumbImgH, $thumbFile);  
			        break;
			    case 3: 
			        imagepng( $thumbImgH, $thumbFile ); 
			        break;		    
			}  
			imagedestroy($thumbImgH);
			imagedestroy($srcImgH);
		}
	}
?>